<template>
  <el-dialog
    :visible="dialogVisible"
    :close-on-click-modal="false"
    title="场景管理"
    width="700px"
    @close="handleCancel">

    <div class="scene-set">
      <div class="scene-tips">您可通过拖拽管理标签</div>

      <flexbox
        align="center"
        justify="center"
        class="scene-list">
        <div class="scene-list-box">
          <flexbox class="scene-list-head">
            <el-checkbox
              :indeterminate="isLeftIndeterminate"
              v-model="checkLeftAll"
              @change="handleLeftCheckAllChange"/>
            <div class="scene-list-head-name">显示的标签</div>
            <div class="scene-list-head-detail">{{ leftCheckItems.length + '/' + checkedLeftData.length }}</div>
          </flexbox>
          <div class="scene-list-body">
            <flexbox
              v-for="(item, index) in checkedLeftData"
              v-if="item.isDefault == 2"
              :key="index"
              class="list-item">
              <div
                :class="{'default-mark-active': item.sceneId == defaultId}"
                class="default-mark"/>
              <el-checkbox
                v-model="item.check"
                :disabled="true"
                class="list-item-check"
                @change="leftCheckItemChange"/>
              <div class="list-item-name">{{ item.name }}</div>
              <div class="list-item-handle">
                <el-dropdown
                  trigger="click"
                  @command="defaultHandle">
                  <i
                    class="el-icon-arrow-down"
                    @click="itemHandle('default', item, index)"/>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>设置为默认标签</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </flexbox>
            <draggable
              v-model="checkedLeftData"
              :move="leftMove"
              :options="{group: 'list',forceFallback:false, fallbackClass:'draggingStyle'}"
              style="min-height: 100px;"
              @end="leftMoveEnd">
              <flexbox
                v-for="(item, index) in checkedLeftData"
                v-if="item.isDefault != 2"
                :key="index"
                class="list-item">
                <div
                  :class="{'default-mark-active': item.sceneId == defaultId}"
                  class="default-mark"/>
                <el-checkbox
                  v-model="item.check"
                  class="list-item-check"
                  @change="leftCheckItemChange"/>
                <div class="list-item-name">{{ item.name }}</div>
                <div class="list-item-handle">
                  <i
                    class="el-icon-edit"
                    @click="itemHandle('update', item, index)"/>
                  <i
                    class="el-icon-delete"
                    @click="itemHandle('delete', item, index)"/>
                  <el-dropdown @command="defaultHandle">
                    <i
                      class="el-icon-arrow-down"
                      @click="itemHandle('default', item, index)"/>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>设置为默认标签</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </flexbox>
            </draggable>

          </div>
        </div>

        <div class="scene-middle-list">
          <el-button
            :class="{'scene-middle-button-select':rightCheckItems.length > 0}"
            :disabled="rightCheckItems.length == 0"
            class="scene-middle-left-button"
            @click="changePosition('left')">
            <i class="el-icon-arrow-left scene-middle-icon"/>
          </el-button>
          <el-button
            :class="{'scene-middle-button-select':leftCheckItems.length > 0}"
            :disabled="leftCheckItems.length == 0"
            class="scene-middle-right-button"
            @click="changePosition('right')">
            <i class="el-icon-arrow-right scene-middle-icon"/>
          </el-button>
        </div>

        <div class="scene-list-box">
          <flexbox class="scene-list-head">
            <el-checkbox
              :indeterminate="isRightIndeterminate"
              v-model="checkRightAll"
              @change="handleRightCheckAllChange"/>
            <div class="scene-list-head-name">隐藏的标签</div>
            <div class="scene-list-head-detail">{{ rightCheckItems.length + '/' + checkedRightData.length }}</div>
          </flexbox>
          <div class="scene-list-body">
            <draggable
              v-model="checkedRightData"
              :move="rightMove"
              :options="{group: 'list',forceFallback:false, fallbackClass:'draggingStyle'}"
              style="min-height: 100px;"
              @end="rightMoveEnd">
              <flexbox
                v-for="(item, index) in checkedRightData"
                :key="index"
                class="list-item">
                <el-checkbox
                  v-model="item.check"
                  style="margin-left:9px;"
                  class="list-item-check"
                  @change="rightCheckItemChange"/>
                <div class="list-item-name">{{ item.name }}</div>
              </flexbox>
            </draggable>
          </div>
        </div>
      </flexbox>

      <div class="handle-bar">
        <div
          class="handle-bar-add"
          @click="addAndEditScene('add',{})">+ 新建场景</div>
      </div>
    </div>

    <div slot="footer">
      <el-button
        @click="handleCancel">
        取消
      </el-button>
      <el-button
        type="primary"
        @click="handleConfirm">
        保存
      </el-button>
    </div>

    <scene-create
      v-if="showSceneCreate"
      :type="type"
      :id="editId"
      @update="getSceneList"
      @close="showSceneCreate = !showSceneCreate" />
  </el-dialog>
</template>

<script>
import {
  jxcSceneSetDefaultAPI,
  jxcSceneDeleteByIdAPI,
  jxcSceneQueryConfigAPI,
  jxcSceneUpdateConfigAPI
} from '@/api/jxc/scene'

import draggable from 'vuedraggable'
import SceneCreate from './SceneCreate'

import jxcTypes from '../../jxcTypes'
// import { isEmpty } from '@/utils/types'

export default {
  name: 'SceneSet',
  components: {
    draggable,
    SceneCreate
  },
  props: {
    // 进销存类型
    type: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: true,
      defaultId: '', // 默认场景id

      isLeftIndeterminate: false, // 标注头部是多选框效果
      checkLeftAll: false, // 关联全选操作多选框
      checkedLeftData: [], // 数据源
      leftCheckItems: [], // 选择的数据源

      isRightIndeterminate: false,
      checkRightAll: false,
      checkedRightData: [],
      rightCheckItems: [],

      moveItem: {}, // 移动中的item
      handleDefaultItem: {}, // 设置默认的中间item

      showSceneCreate: false,
      editId: null
    }
  },
  computed: {
    typeObj() {
      return jxcTypes[this.type]
    }
  },
  created() {
    this.getSceneList()
  },
  methods: {
    getSceneList() {
      jxcSceneQueryConfigAPI({
        label: this.typeObj.label
      }).then(res => {
        console.log('res: ', res.data)
        this.checkedLeftData = res.data.value.map(item => {
          item.check = false
          return item
        })

        this.checkedRightData = res.data.hideValue.map(item => {
          item.check = false
          return item
        })

        const defaultScene = this.checkedLeftData.filter(item => {
          return item.defaultScene === 1
        })
        // 如果有默认场景
        if (defaultScene && defaultScene.length > 0) {
          this.defaultId = defaultScene[0].sceneId
        } else {
          this.defaultId = ''
        }
      }).catch(() => {})
    },

    /**
     * 确定选择
     */
    handleConfirm() {
      if (this.loading) return
      // 如果选择默认的 不包含在左侧列表 重置为没有默认
      const findArr = this.checkedLeftData.filter(o => o.sceneId == this.defaultId)
      if (findArr.length === 0) this.defaultId = ''

      const params = {
        label: this.typeObj.label,
        noHideIds: this.checkedLeftData.map(o => o.sceneId).join(','),
        hideIds: this.checkedRightData.map(o => o.sceneId).join(',')
      }
      console.log('save: ', params)

      this.loading = true
      jxcSceneUpdateConfigAPI(params).then(() => {
        this.loading = false
        this.$message.success('操作成功')
        this.$emit('update')
        this.handleCancel()
      }).catch(() => {
        this.loading = false
      })
    },

    /** 事项操作 */
    itemHandle(type, item, index) {
      if (type === 'update') {
        this.addAndEditScene('update', item)
      } else if (type === 'delete') {
        this.$confirm('您确定要删除这一条数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          jxcSceneDeleteByIdAPI({
            sceneId: item.sceneId
          }).then(() => {
            this.$message.success('删除成功')
            this.checkedLeftData.splice(index, 1)
            this.leftCheckItemChange()
            this.$emit('update')
          }).catch(() => {})
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      } else if (type === 'default') {
        this.handleDefaultItem = item
      }
    },

    /**
     * 设置为默认场景
     */
    defaultHandle() {
      jxcSceneSetDefaultAPI({
        sceneId: this.handleDefaultItem.sceneId,
        label: this.typeObj.label
      }).then(() => {
        this.$message.success('操作成功')
        this.defaultId = this.handleDefaultItem.sceneId
      }).catch(() => {})
    },

    /** 添加编辑场景 */
    addAndEditScene(type, data) {
      if (type === 'update') {
        this.editId = data.sceneId
        this.showSceneCreate = true
      } else {
        this.editId = null
        this.showSceneCreate = true
      }
    },

    /**
     * 取消选择
     */
    handleCancel() {
      this.$emit('close')
    },

    /** 拖拽操作 */
    rightMove(obj) {
      this.moveItem = obj.draggedContext.element
    },
    rightMoveEnd(evt) {
      this.moveItem.check = false
      this.leftCheckItemChange()
      this.rightCheckItemChange()
    },
    leftMove(obj) {
      this.moveItem = obj.draggedContext.element
    },
    leftMoveEnd(evt) {
      this.moveItem.check = false
      this.leftCheckItemChange()
      this.rightCheckItemChange()
    },

    // 选择全部
    handleLeftCheckAllChange(value) {
      if (value) {
        this.isLeftIndeterminate = false
      }
      this.checkedLeftData.forEach(item => {
        item.check = item.isDefault == 2 ? false : value
      })

      this.leftCheckItems = value ? this.checkedLeftData.filter(item => {
        return item.check
      }) : []
    },
    leftCheckItemChange() {
      this.leftCheckItems = this.checkedLeftData.filter(item => {
        return item.check == true
      })
      if (this.leftCheckItems.length > 0) {
        if (this.leftCheckItems.length == this.checkedLeftData.length) {
          this.checkLeftAll = true
          this.isLeftIndeterminate = false
        } else {
          this.checkLeftAll = false
          this.isLeftIndeterminate = true
        }
      } else {
        this.checkLeftAll = false
        this.isLeftIndeterminate = false
      }
    },
    // 选择全部
    handleRightCheckAllChange(value) {
      if (value) {
        this.isRightIndeterminate = false
      }
      this.checkedRightData.forEach(item => {
        item.check = value
      })
      this.rightCheckItems = value ? this.checkedRightData : []
    },
    rightCheckItemChange() {
      this.rightCheckItems = this.checkedRightData.filter(item => {
        return item.check == true
      })
      if (this.rightCheckItems.length > 0) {
        if (this.rightCheckItems.length == this.checkedRightData.length) {
          this.checkRightAll = true
          this.isRightIndeterminate = false
        } else {
          this.checkRightAll = false
          this.isRightIndeterminate = true
        }
      } else {
        this.checkRightAll = false
        this.isRightIndeterminate = false
      }
    },

    // 按钮操作
    changePosition(type) {
      const self = this
      // 从右往左
      if (type == 'left') {
        this.checkedRightData = this.checkedRightData.filter(item => {
          let remove = false
          self.rightCheckItems.forEach(element => {
            if (item.sceneId == element.sceneId) {
              remove = true
            }
          })
          return !remove
        })

        this.rightCheckItems.forEach(element => {
          element.check = false
          self.checkedLeftData.push(element)
        })

        this.rightCheckItems = []
        this.isRightIndeterminate = false
        this.checkRightAll = false
      } else {
        this.checkedLeftData = this.checkedLeftData.filter(item => {
          let remove = false
          self.leftCheckItems.forEach(element => {
            if (item.sceneId == element.sceneId) {
              remove = true
            }
          })
          return !remove
        })

        this.leftCheckItems.forEach(element => {
          element.check = false
          self.checkedRightData.push(element)
        })

        this.leftCheckItems = []
        this.isLeftIndeterminate = false
        this.checkLeftAll = false
      }

      // 刷新两侧选中效果
      this.leftCheckItemChange()
      this.rightCheckItemChange()
    }
  }
}
</script>

<style scoped lang="scss">
.default-mark {
  width: 4px;
  height: 4px;
  border-radius: 2px;
  margin-right: 5px;
}
.default-mark-active {
  background-color: $xr-color-primary;
}

.scene-set {
  .scene-tips {
    font-size: 12px;
    color: #aaa;
    padding-bottom: 5px;
  }

  .scene-list {
    user-select: none;

    .scene-list-box {
      flex: 1;
      border: 1px solid $xr-border-line-color;
      border-radius: 2px;
      height: 300px;
      position: relative;
      padding: 15px;
    }
    .scene-middle-list {
      width: 50px;
      text-align: center;
      button {
        border: 1px solid #cccccc;
        width: 34px;
        height: 34px;
        border-radius: 17px;
        background-color: #f5f7fa;
      }
      .scene-middle-icon {
        color: #cccccc;
        font-size: 14px;
      }
      .scene-middle-left-button {
      }
      .scene-middle-right-button {
        margin-top: 15px;
        margin-left: 0;
      }

      .scene-middle-button-select {
        border: 1px solid $xr-color-primary !important;
        background-color: $xr-color-primary !important;
        .scene-middle-icon {
          color: white !important;
        }
      }
    }
    .scene-list-head {
      padding-bottom: 15px;
      padding-left: 9px;
      border-bottom: 1px dashed $xr-border-line-color;
      font-size: 13px;
      .scene-list-head-name {
        color: #333;
        flex: 1;
        margin: 0 8px;
      }

      .scene-list-head-detail {
        color: #aaa;
      }
    }
    .scene-list-body {
      padding: 5px 0;
      height: 240px;
      position: relative;
      overflow-y: auto;
    }

    .list-item {
      padding: 5px 0;
      background-color: white;
      cursor: pointer;
      .list-item-check {
        margin-right: 8px;
      }
      .list-item-name {
        font-size: 13px;
        color: #333;
        flex: 1;
      }
      .list-item-handle {
        flex-shrink: 0;
        display: none;
        i {
          color: #aaa;
          font-size: 12px;
          margin-right: 5px;
        }
        i:hover {
          color: $xr-color-primary;
        }
      }
    }

    .list-item:hover {
      .list-item-handle {
        display: block;
      }
    }
  }

  .handle-bar {
    font-size: 12px;
    .handle-bar-add {
      cursor: pointer;
      color: #2362FB;
      padding: 20px 10px 0;
    }
    .handle-bar-save {
      position: relative;
      height: 30px;
      button {
        float: right;
        margin-right: 10px;
      }
    }
  }
}
</style>
